package com.monster.spring.cloud.alibaba.consumer01.controller;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * description:
 *
 * @author Yuanml on 2021/5/26 21:47
 */
@RestController
@RequestMapping("/test")
public class TestController {
    @Resource
    private LoadBalancerClient loadBalancerClient;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/hello/{name}")
    public String test(@PathVariable("name") String name) {
        ServiceInstance serviceInstance = loadBalancerClient.choose("provider01");
        String url = String.format("http://%s:%s/echo/hello/%s", serviceInstance.getHost(), serviceInstance.getPort(), name);
        System.out.println("url = " + url);
        // 下行代码将报错，需注释掉restTemplate上的@LoadBalanced注解
        return restTemplate.getForObject(url, String.class);
    }

    @GetMapping("/hello2/{name}")
    public String testLoadBalancerByRestTemplate(@PathVariable("name") String name) {
        String url = String.format("http://%s/echo/hello/%s", "provider01", name);
        System.out.println("url = " + url);
        return restTemplate.getForObject(url, String.class);
    }
}
